﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace VANAD.WindowsLive.Writer.InsertFavoritePlugin.BO
{
    public class Favorite
    {
        // Fields
        private string _linkTitle;
        private Uri _linkUrl;
        private string _displayPattern = @"<a title='{0}' href='{1}'>{1}</a>";

        // Properties
        public string Title
        {
            get { return _linkTitle; }
        }

        public Uri Url
        {
            get { return _linkUrl; }
        }

        public string DisplayPattern
        {
            get { return _displayPattern; }
        }

        public string HTMLInsertText 
        { 
            get 
            {
                return string.Format(_displayPattern, _linkTitle, _linkUrl.ToString());
            } 
        }

        public string DisplayPatternNoHTMLMarkup
        {
            get
            {
                return RemoveHTMLElements(HTMLInsertText);
            }
        }

        // Methods
        private string RemoveHTMLElements(string html)
        {
            int startIndex = html.IndexOf('<');
            int count = html.IndexOf('>') - startIndex + 1;

            string resultHtml = html.Remove(startIndex, count);

            if (resultHtml.IndexOf('<') >= 0 && resultHtml.IndexOf('>') >= 0)
                resultHtml = RemoveHTMLElements(resultHtml);

            return resultHtml;
        }

        public Favorite(string title, string url)
        {
            this._linkTitle = title;
            this._linkUrl = new Uri(url);
        }

        public Favorite(string title, string url, string displayPattern)
        {
            this._displayPattern = displayPattern;
            this._linkTitle = title;
            this._linkUrl = new Uri(url);
        }

        public Favorite(FileInfo fi, string displayPattern)
        {
            this._linkTitle = fi.Name.Replace(fi.Extension, "");
            this._linkUrl = new Uri(this.getUrlFromLinkFile(fi.FullName));
            this._displayPattern = displayPattern;
        }

        private string getUrlFromLinkFile(string file)
        {
            StreamReader sr = null; string content;
            if (!file.EndsWith(".url")) return "";
            try
            {
                sr = new StreamReader(file);
                content = sr.ReadToEnd();
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }

            if (content.Length == 0)
                return "";

            int startI = content.IndexOf("URL=");
            if (startI == -1)
                return "";

            startI += 4;
            int endI = content.IndexOf(Environment.NewLine, startI + 1);

            return content.Substring(startI, endI - startI);
        }
    }
}
